package com.headwind.multi.datasource.config;

import com.headwind.multi.datasource.DynamicDataSource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/13
 * @description : JPA事务管理初始化处理
 */
@Log4j2
@Component
public class JpaEntityManagerConfiguration {

    private final JpaProperties jpaProperties;
    private final EntityManagerFactoryBuilder builder;

    /**
     * 获取实体类的包路径
     */
    @Value("${spring.datasource.entityPackage}")
    private String entityPackage;

    /**
     * 主数据源
     */
    @Resource(name = DataSourceConfig.MASTER_DATASOURCE)
    private DataSource masterDataSource;

    /**
     * 读数据源
     */
    @Resource(name = DataSourceConfig.READ_DATASOURCE)
    private DataSource readDataSource;

    public JpaEntityManagerConfiguration(JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
        this.jpaProperties = jpaProperties;
        this.builder = builder;
    }


    /**
     * AbstractRoutingDataSource类中设定数据源
     *
     * @return 数据源
     */
    @Bean(name = "routingDataSource")
    public AbstractRoutingDataSource routingDataSource() {
        DynamicDataSource proxy = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>(4);
        targetDataSources.put(DataSourceConfig.READ_DATASOURCE, readDataSource);
        // 设定默认数据源
        proxy.setDefaultTargetDataSource(masterDataSource);
        // 设定
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

    /**
     * 实体管理Bean的初始化
     *
     * @return LocalContainerEntityManagerFactoryBean
     */
    @Bean(name = "entityManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
            @Qualifier("routingDataSource") AbstractRoutingDataSource routingDataSource) {
        Map<String, String> properties = jpaProperties.getProperties();
        properties.put("hibernate.physical_naming_strategy",
                "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        properties.put("hibernate.hbm2ddl.auto", "validate");
        // 设定查询的超时时间
        properties.put("javax.persistence.query.timeout", "60000");
        log.info("Initializing Entity Manager Factory Bean");
        return builder.dataSource(routingDataSource)
                .properties(properties).packages(entityPackage)
                .persistenceUnit("readPersistenceUnit").build();
    }

    /**
     * 实体管理工厂类初始化
     *
     * @return EntityManagerFactory
     */
    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory(@Qualifier("entityManagerFactoryBean") LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
        log.info("Entity Manager Factory initialization completed");
        return entityManagerFactoryBean.getObject();
    }

    /**
     * JPA事务管理初始化
     *
     * @return PlatformTransactionManager
     */
    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
        log.info("JPA Transaction Manager initialization completed");
        return new JpaTransactionManager(entityManagerFactory);
    }
}